package main

import (
	"net/http"
	"encoding/json"
	"log"
	"runtime/debug"
)

func service(w http.ResponseWriter, r *http.Request) {
	values := make(map[string]string)
	values["status"] = "UP"
	if json, err := json.Marshal(values); err != nil {
		w.Write([]byte("err"))
	} else {
		w.Write(json)
	}
}

func userInfo(w http.ResponseWriter,r *http.Request){
	values := make(map[string]string)
	values["name"] = "wyx"
	values["sex"] = "feman"
	if json, err := json.Marshal(values); err != nil {
		w.Write([]byte("err"))
	} else {
		w.Write(json)
	}
}

//tips:巧用闭包避免程序运行时出错崩溃-->来自《go语言编程166page》
//noinspection ALL
func safeHandler(fn http.HandlerFunc) http.HandlerFunc{
	return func(w http.ResponseWriter,r *http.Request){
		w.Header().Set("Content-type", "application/json");
		defer func(){
		 if e,ok:=recover().(error);ok{
			 http.Error(w,e.Error(),http.StatusInternalServerError)
			 log.Println("WARN: panic in %v - %v", fn, e)
			 log.Println(string(debug.Stack()))
		 }
		}()
	      fn(w,r)
	}
}

func home(w http.ResponseWriter,r *http.Request){
	values := make(map[string]string)
	values["title"] = "欢迎你io"
	if json, err := json.Marshal(values); err != nil {
		w.Write([]byte("err"))
	} else {
		w.Write(json)
	}
}

func main() {
	http.HandleFunc("/",safeHandler(home))
	http.HandleFunc("/health.json", safeHandler(service))
	http.HandleFunc("/userInfo", safeHandler(userInfo))
	http.ListenAndServe(":8090", nil)
}
